from data import *
from PySide6.QtWidgets import QApplication
from task import *
import BuildingUI as B
import pprint
import cv2
import matplotlib.pyplot as plt

# TODO: 暂停执行任务
# TODO: 任务执行结果明细
# TODO: 统计持久化
# TODO: 快进任务
# TODO: 准备支持仙树升级加速
# TODO: 准备支持宗门自动看广告、自动锤炼弟子、自动出师
# TODO: 准备支持仙友自动寻访
# TODO: 不用while 200，直接创建定时任务
# TODO: 准备支持镇妖塔自动挑战
# TODO: 准备支持定时砍仙树(砍到某一等级)
# TODO: 准备支持自动决斗
# TODO: 准备支持自动...
# TODO: 用状态+依赖来做


class FudiScriptUI(B.IWidget):
    def __init__(self):
        self.reactives = B.ReactiveContainer()
        super().__init__(
            B.GroupBox(
                title="福地",
                layout=B.VBoxLayout(
                    children=[
                        B.HBoxLayout(
                            children=[
                                B.PushButton(
                                    text="开始探寻",
                                    onClicked=lambda: TaskQueue().postTask(
                                        FudiExploreTask()
                                    ),
                                ),
                                B.Label(
                                    text=B.PropertyBinding(
                                        FudiScriptData().status, B.BindMode.Set_Spread
                                    ),
                                ),
                                B.Label(
                                    text=B.PropertyBinding(
                                        self.reactives.createComputed(
                                            lambda: f"轮数:{FudiScriptData().round_number.get()}"
                                        ),
                                        B.BindMode.Set_Spread,
                                    )
                                ),
                                B.Stretch(),
                            ]
                        ),
                        B.HBoxLayout(
                            children=[
                                B.CheckBox(
                                    text=B.PropertyBinding(
                                        self.reactives.createComputed(
                                            lambda: f"3级桃子: {FudiScriptData().tz3_number.get()}"
                                        ),
                                        B.BindMode.Set_Spread,
                                    ),
                                    checked=B.PropertyBinding(
                                        FudiScriptData().checked_tz3,
                                        B.BindMode.Set_Feedback,
                                    ),
                                ),
                                B.CheckBox(
                                    text=B.PropertyBinding(
                                        self.reactives.createComputed(
                                            lambda: f"4级桃子: {FudiScriptData().tz4_number.get()}"
                                        ),
                                        B.BindMode.Set_Spread,
                                    ),
                                    checked=B.PropertyBinding(
                                        FudiScriptData().checked_tz4,
                                        B.BindMode.Set_Feedback,
                                    ),
                                ),
                                B.CheckBox(
                                    text=B.PropertyBinding(
                                        self.reactives.createComputed(
                                            lambda: f"5级桃子: {FudiScriptData().tz5_number.get()}"
                                        ),
                                        B.BindMode.Set_Spread,
                                    ),
                                    checked=B.PropertyBinding(
                                        FudiScriptData().checked_tz5,
                                        B.BindMode.Set_Feedback,
                                    ),
                                ),
                                B.Stretch(),
                            ]
                        ),
                    ]
                ),
            ).widget
        )


class ToolsUI(B.IWidget):
    def __init__(self):
        self.reactives = B.ReactiveContainer()
        super().__init__(
            B.GroupBox(
                title="工具",
                layout=B.VBoxLayout(
                    children=[
                        B.HBoxLayout(
                            children=[
                                B.PushButton(
                                    text="刷新设备",
                                    onClicked=lambda: self.flushDevices(),
                                ),
                                B.ComboBox(
                                    minimumWidth=200,
                                    model=B.StringListModel(ToolsData().devices),
                                    currentText=B.PropertyBinding(
                                        ToolsData().current_device,
                                        B.BindMode.Feedback,
                                    ),
                                ),
                                B.PushButton(
                                    text="连接设备",
                                    onClicked=lambda: ADBEnv().connect(
                                        ToolsData().current_device.get()
                                    ),
                                ),
                                B.PushButton(
                                    text="断开设备",
                                    onClicked=lambda: ADBEnv().disconnect(),
                                ),
                                B.Stretch(),
                            ]
                        ),
                        B.HBoxLayout(
                            children=[
                                B.PushButton(
                                    text="截图",
                                    onClicked=lambda: ADBEnv().save_screen_shot(),
                                ),
                                B.Stretch(),
                            ]
                        ),
                        B.HBoxLayout(
                            children=[
                                B.PushButton(
                                    text="刷新图片",
                                    onClicked=lambda: self.flushImages(),
                                ),
                                B.ComboBox(
                                    minimumWidth=200,
                                    model=B.StringListModel(ToolsData().images),
                                    currentText=B.PropertyBinding(
                                        ToolsData().current_image,
                                        B.BindMode.Feedback,
                                    ),
                                ),
                                B.PushButton(
                                    text="识别",
                                    onClicked=lambda: self.recognizeImage(),
                                ),
                                B.Stretch(),
                            ]
                        ),
                        B.ListView(model=B.StringListModel(ToolsData().tasks)),
                    ]
                ),
            ).widget
        )
        self.flushDevices()
        self.flushImages()

    def flushDevices(self):
        ToolsData().devices.set(ADBEnv().devices())

    def flushImages(self):
        # 读取images文件夹下的所有图片
        images = []
        for file in os.listdir("images"):
            if file.endswith(".png"):
                images.append(file)
        ToolsData().images.set(images)
        ADBEnv().flush_images()

    def recognizeImage(self):
        tools = ToolsData()
        if tools.current_image.get() != "":
            adb = ADBEnv()
            current_image = adb.get_image(tools.current_image.get())
            ss = adb.screen_shot()
            result = aircv.find_all_template(ss, current_image)
            result2 = aircv.find_template(ss, current_image)
            print(f"{tools.current_image.get()}的识别结果是:")
            pprint.pprint(result)
            pprint.pprint(result2)
            if result:
                for item in result[:7]:
                    p1 = item["rectangle"][0]
                    p2 = item["rectangle"][3]
                    ss = cv2.rectangle(ss, p1, p2, color=(0, 255, 0), thickness=2)
                    ss = cv2.putText(
                        ss,
                        str(item["confidence"])[:5],
                        p2,
                        cv2.FONT_HERSHEY_SIMPLEX,
                        1,
                        (0, 255, 0),
                        2,
                    )
                plt.imshow(ss)
                plt.show()
                plt.get_current_fig_manager().window.showMaximized()


if __name__ == "__main__":
    app = QApplication([])
    window = B.MainWindow(
        centralWidget=B.Widget(
            layout=B.VBoxLayout(
                children=[
                    FudiScriptUI(),
                    ToolsUI(),
                    B.Stretch(),
                ]
            ),
        ),
    )
    window.show()
    app.exec()
    TaskQueue().running = TaskQueueState.Finished
